package com.cskaoyan.pool;

import com.cskaoyan.utils.JDBCUtils2;

import java.io.FileInputStream;
import java.sql.Connection;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 创建日期: 2022/11/18 09:51
 *
 * @author ciggar
 *
 * 添加扩容的逻辑
 *
 * 但是目前的参数都是写死的，我们应该把这些参数做成可配置化
 *
 *
 */
public class MyConnectionPoolV3 {

    static int INIT_SIZE = 8;
    static int INCREMENT = 5;
    static int MIN_SIZE = 2;


    // 连接的容器（可选 ：ArrayList | LinkedList | 数组 | 队列 ）
    // 从头部存，从尾部取
    static LinkedList<Connection> pool;

    static {

        try {

            // 读取配置文件
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(fileInputStream);

            String initSize = properties.getProperty("init_size");
            String increment = properties.getProperty("increment");
            String minSize = properties.getProperty("min_size");

            // 如果没有值，使用默认配置；如果配置文件中有值，再去赋值
            if (initSize.length() > 0) INIT_SIZE = Integer.valueOf(initSize);
            if (increment.length() > 0) INCREMENT = Integer.valueOf(increment);
            if (minSize.length() > 0) MIN_SIZE = Integer.valueOf(minSize);

        }catch (Exception ex) {
            ex.printStackTrace();
            throw  new RuntimeException("读取配置文件失败！");
        }

        // 初始化数据库连接池
        pool = new LinkedList<Connection>();
        addIncrement(INIT_SIZE);


    }


    // 获取连接
    public static Connection getConnection(){

        // 扩容
        if (pool.size() < MIN_SIZE) {
            addIncrement(INCREMENT);
        }

        Connection connection = pool.removeLast();
        return connection;
    }

    // 回收连接
    public static void returnConnection(Connection connection){

        pool.addFirst(connection);

    }


    // 扩容的方法
    private static void addIncrement(int size) {
        if (size < 1) return;
        for (int i = 0; i < size; i++) {
            Connection newConnection = JDBCUtils2.getNewConnection();
            pool.addFirst(newConnection);
        }

    }
}
